package cece.service.impl;

import cece.entity.User;
import cece.mapper.UserMapper;
import cece.service.UserService;
import cece.utils.RedisUtils;
import cece.utils.SendSmsUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public boolean userRegister(User user) {
        System.out.println(user.getPassword());
        User findUser = userMapper.findByTelephone(user.getTelephone());
        if (findUser == null) {
            Md5Hash md5Hash = new Md5Hash(user.getPassword(),"cc");
            user.setPassword(md5Hash.toString());
            int result = userMapper.userRegister(user);
            if (result > 0) {
                return true;
            }
        }
        return false;
    }

    @Override
    public User findByTelephone(String telephone) {
        try {
            User user = userMapper.findByTelephone(telephone);
            if (user != null) {
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String getCode(String telephone) {
        String code = SendSmsUtils.code();
        redisUtils.set(telephone, code);
        return SendSmsUtils.sendSms(telephone, code);
    }


    @Override
    public User login(User user) {
        // 根据用户手机查询数据库
        User findUser = userMapper.findByTelephone(user.getTelephone());
        return findUser;
    }
}
